<template>
  <div id="userLoginView">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      style="max-width: 480px; margin: 0 auto"
      @submit="handleSubmit"
    >
      <a-form-item field="userName" label="用户名" validate-trigger="blur">
        <a-input v-model="form.userName" placeholder="请输入用户名..." />
      </a-form-item>
      <a-form-item field="userAccount" label="账号" validate-trigger="blur">
        <a-input v-model="form.userAccount" placeholder="请输入账号..." />
      </a-form-item>
      <a-form-item
        field="userPassword"
        label="密码"
        tooltip="密码不少于 8 位"
        validate-trigger="blur"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码..."
        />
      </a-form-item>
      <a-form-item
        field="checkPassword"
        label="确认密码"
        validate-trigger="blur"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="确认密码..."
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button html-type="submit" type="primary">Submit</a-button>
          <a-button @click="$refs.formRef.resetFields()">Reset</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService } from "../../../generated";
import { useRouter } from "vue-router";
import message from "@arco-design/web-vue/es/message";

const form = reactive({
  userName: "",
  userAccount: "",
  userPassword: "",
  checkPassword: "",
}) as UserControllerService;

const rules = {
  userName: [
    {
      required: true,
      message: "用户名不可为空",
    },
  ],
  userAccount: [
    {
      required: true,
      message: "账号不可为空",
    },
  ],
  userPassword: [
    {
      required: true,
      message: "密码不少于 8 位",
    },
    {
      validator: (value, cb) => {
        if (value.length < 8) {
          cb("密码不少于 8 位");
        } else {
          cb();
        }
      },
    },
  ],
  checkPassword: [
    {
      required: true,
      message: "确认密码不可为空",
    },
    {
      validator: (value, cb) => {
        if (value !== form.userPassword) {
          cb("两次密码不同");
        } else {
          cb();
        }
      },
    },
  ],
};

const router = useRouter(); // 路由

// 提交处理函数
const handleSubmit = async () => {
  const res = await UserControllerService.userRegisterUsingPost(form);
  if (res.code === 0) {
    // 注册成功
    router.push("/user/login");
  } else {
    message.error("注册失败," + res.message);
  }
};
</script>
